import json
import time
from typing import Dict, List, Optional
from datetime import datetime

from json_translate import convert_excel_to_json
import os

# 获取JSON文件路径
json_path = convert_excel_to_json("/Users/mike.chen/Desktop/伪桌面（9-10月）/oop期末_副本/greedy_-snakes_2/Greedy Snakes 2 frame/ali_bao_bao/data/商品数据集.xlsx")
def bi(cn: str, en: str) -> str:
    """返回中英对照文本/Return bilingual text."""
    return f"{cn} ({en})"
class User:
    """用户基类（区分顾客和商家）"""
    def __init__(self, user_id: str, user_type: str):
        self.user_id = user_id
        self.user_type = user_type  # 'customer' 或 'merchant'


class Customer(User):
    """顾客类"""
    def __init__(self, user_id: str, nickname: str):
        super().__init__(user_id, 'customer')
        self.nickname = nickname
        self.search_history = []  # 搜索历史
    
    def add_search_history(self, keyword: str, results_count: int):
        """添加搜索历史"""
        search_record = {
            "keyword": keyword,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M"),
            "results_count": results_count
        }
        # 避免重复记录
        if not self.search_history or self.search_history[-1]["keyword"] != keyword:
            self.search_history.append(search_record)
            # 只保留最近10次搜索
            if len(self.search_history) > 10:
                self.search_history = self.search_history[-10:]
    
    def get_search_history(self):
        """获取搜索历史"""
        return self.search_history


class Merchant(User):
    """商家类"""
    def __init__(self, user_id: str, shop_name: str):
        super().__init__(user_id, 'merchant')
        self.shop_name = shop_name


class Product:
    """商品基类（含完整功能）"""
    def __init__(self, 
                 name: str, 
                 province: str, 
                 prize: float, 
                 id_: str, 
                 province_id: str, 
                 merchant_id: str,  # 关联商家ID
                 kind: str,
                 comments: Optional[List] = None,  # 多条评价
                 modify_logs: Optional[List] = None  # 修改日志
                 ):
        self.name = name
        self.province = province
        self.prize = prize
        self.id = id_
        self.province_id = province_id
        self.merchant_id = merchant_id  # 用于权限控制
        self.kind = kind
        self.comments = comments or []  # 评价列表
        self.modify_logs = modify_logs or []  # 修改日志

    def add_comment(self, customer: Customer, comment_data: Dict) -> None:
        """顾客添加评价"""
        new_comment = {
            "comment_id": f"cmt_{int(time.time())}",
            "customer_id": customer.user_id,
            "nickname": customer.nickname,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M"),
            "product_rating": comment_data["商品满意度"],
            "merchant_rating": comment_data["商家满意度"],
            "logistics_rating": comment_data["物流满意度"],
            "text": comment_data["文字评价"],
            "likes": 0,
            "liked_by": [],  # 记录点赞用户ID
            "replies": [],  # 回复列表
            "merchant_reply": None  # 商家回复
        }
        self.comments.append(new_comment)
        self._save_to_file()
        print(bi("评价提交成功！", "Review submitted successfully!"))

    def like_comment(self, customer: Customer, comment_id: str) -> bool:
        """顾客点赞评价"""
        for comment in self.comments:
            if comment["comment_id"] == comment_id:
                if customer.user_id in comment["liked_by"]:
                    print(bi("您已点赞过这条评价！", "You have already liked this review!"))
                    return False  # 已点赞
                comment["likes"] += 1
                comment["liked_by"].append(customer.user_id)
                self._save_to_file()
                print(bi(f"点赞成功！当前点赞数：{comment['likes']}", f"Like added! Current likes: {comment['likes']}"))
                return True
        print(bi("未找到该评价！", "Review not found!"))
        return False

    def reply_to_comment(self, customer: Customer, comment_id: str, reply_text: str) -> bool:
        """顾客回复评价"""
        for comment in self.comments:
            if comment["comment_id"] == comment_id:
                comment["replies"].append({
                    "reply_id": f"rpl_{int(time.time())}",
                    "customer_id": customer.user_id,
                    "nickname": customer.nickname,
                    "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M"),
                    "text": reply_text
                })
                self._save_to_file()
                print(bi("回复成功！", "Reply posted!"))
                return True
        print(bi("未找到该评价！", "Review not found!"))
        return False

    def merchant_reply(self, merchant: Merchant, comment_id: str, reply_text: str) -> bool:
        """商家回复评价（权限校验）"""
        if merchant.user_id != self.merchant_id:
            print(bi("权限错误：您无权回复其他商家的商品评价！", "Permission error: You cannot reply to other merchants' product reviews!"))
            return False
        
        for comment in self.comments:
            if comment["comment_id"] == comment_id:
                comment["merchant_reply"] = {
                    "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M"),
                    "text": reply_text,
                    "shop_name": merchant.shop_name
                }
                self._save_to_file()
                print(bi("回复成功！已显示为官方回复", "Reply added as official response"))
                return True
        print(bi("未找到该评价！", "Review not found!"))
        return False

    def filter_comments(self, filter_type: str, sort_type: str) -> List:
        """筛选评价：filter_type(好评/中评/差评)，sort_type(最新/最热)"""
        filtered = []
        for comment in self.comments:
            # 计算综合评分（取均值）
            total = sum([
                len(comment["product_rating"]),
                len(comment["merchant_rating"]),
                len(comment["logistics_rating"])
            ])
            avg = total / 3

            # 按评价等级筛选
            if filter_type == "好评" and avg >= 4:
                filtered.append(comment)
            elif filter_type == "中评" and 2 < avg < 4:
                filtered.append(comment)
            elif filter_type == "差评" and avg <= 2:
                filtered.append(comment)
            elif filter_type == "全部":
                filtered.append(comment)

        # 排序
        if sort_type == "最新":
            return sorted(filtered, key=lambda x: x["timestamp"], reverse=True)
        elif sort_type == "最热":
            return sorted(filtered, key=lambda x: x["likes"] + len(x["replies"]), reverse=True)
        return filtered

    def update_info(self, merchant: Merchant, new_data: Dict, reason: str) -> bool:
        """商家修改商品信息（带权限校验和日志）"""
        if merchant.user_id != self.merchant_id:
            print(bi("权限错误：您无权修改其他商家的商品！", "Permission error: You cannot modify other merchants' products!"))
            return False

        # 记录修改前的值
        old_data = {}
        if "prize" in new_data:
            old_data["prize"] = self.prize
            self.prize = new_data["prize"]
        if "province" in new_data:
            old_data["province"] = self.province
            self.province = new_data["province"]
        # 已移除库存字段（stock），不再支持库存修改

        # 添加修改日志
        self.modify_logs.append({
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M"),
            "merchant_id": merchant.user_id,
            "shop_name": merchant.shop_name,
            "old_data": old_data,
            "new_data": new_data,
            "reason": reason
        })

        self._save_to_file()
        return True

    @classmethod
    def fuzzy_search(cls, keyword: str) -> List:
        """增强的模糊搜索商品 - 支持多字段搜索"""
        products = cls._load_all_products()
        keyword = keyword.lower().strip()
        results = []
        
        for p in products:
            score = 0
            # 搜索商品名称
            if keyword in p.name.lower():
                if p.name.lower() == keyword:
                    score += 10  # 完全匹配
                elif p.name.lower().startswith(keyword):
                    score += 8   # 开头匹配
                else:
                    score += 5  # 包含匹配
            
            # 搜索商品类别
            if keyword in p.kind.lower():
                score += 3
            
            # 搜索产地
            if keyword in p.province.lower():
                score += 2
            
            # 搜索商品ID
            if keyword in p.id.lower():
                score += 4
            
            # 如果有匹配，添加到结果中
            if score > 0:
                results.append((p, score))
        
        # 按匹配度排序，匹配度相同时按名称排序
        return [p for p, _ in sorted(results, key=lambda x: (-x[1], x[0].name))]

    @classmethod
    def advanced_search(cls, search_criteria: Dict) -> List:
        """高级搜索 - 支持多条件组合搜索"""
        products = cls._load_all_products()
        results = []
        
        for p in products:
            match = True
            
            # 名称搜索
            if 'name' in search_criteria and search_criteria['name']:
                if search_criteria['name'].lower() not in p.name.lower():
                    match = False
            
            # 类别搜索
            if 'kind' in search_criteria and search_criteria['kind']:
                if search_criteria['kind'].lower() not in p.kind.lower():
                    match = False
            
            # 产地搜索
            if 'province' in search_criteria and search_criteria['province']:
                if search_criteria['province'].lower() not in p.province.lower():
                    match = False
            
            # 价格范围搜索
            if 'min_price' in search_criteria and search_criteria['min_price']:
                if p.prize < search_criteria['min_price']:
                    match = False
            
            if 'max_price' in search_criteria and search_criteria['max_price']:
                if p.prize > search_criteria['max_price']:
                    match = False
            
            # 已移除库存字段（stock），不再支持库存过滤
            
            if match:
                results.append(p)
        
        return results

    @classmethod
    def from_name(cls, name: str):
        """通过名称获取商品"""
        products = cls._load_all_products()
        for p in products:
            if p.name == name:
                return p
        return None

    @classmethod
    def get_merchant_products(cls, merchant_id: str) -> List:
        """获取商家名下的所有商品"""
        all_products = cls._load_all_products()
        return [p for p in all_products if p.merchant_id == merchant_id]

    @classmethod
    def _load_all_products(cls) -> List:
        """加载所有商品"""
        try:
            # 使用动态获取的JSON文件路径
            json_file_path = json_path if json_path else "/Users/mike.chen/Desktop/伪桌面（9-10月）/oop期末_副本/greedy_-snakes_2/Greedy Snakes 2 frame/ali_bao_bao/data/商品数据集.json"
            with open(json_file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            products = []
            for item in data:
                # 动态创建对应子类
                kind_cls = {
                    "Food": Food,
                    "Clothing": Clothing,
                    "Book": Book,
                    "Electronic Products": ElectronicProducts,
                    "Daily product": DailyProduct
                }.get(item["Kind"], Product)
                
                product = kind_cls(
                    name=item["Name"],
                    province=item["Province"],
                    prize=item["Prize（yuan)"],
                    id_=item["ID"],
                    province_id=item["ProvinceID"],
                    merchant_id=item.get("MerchantID", ""),
                    kind=item["Kind"],
                    comments=item.get("Comments", []),
                    modify_logs=item.get("ModifyLogs", [])
                )
                products.append(product)
            return products
        except (FileNotFoundError, json.JSONDecodeError):
            return []

    def _save_to_file(self) -> None:
        """保存商品数据到文件"""
        all_products = [p.to_dict() for p in self._load_all_products() if p.id != self.id]
        all_products.append(self.to_dict())
        
        # 使用动态获取的JSON文件路径
        json_file_path = json_path if json_path else "/Users/mike.chen/Desktop/伪桌面（9-10月）/oop期末_副本/greedy_-snakes_2/Greedy Snakes 2 frame/ali_bao_bao/data/商品数据集.json"
        with open(json_file_path, 'w', encoding='utf-8') as f:
            json.dump(all_products, f, ensure_ascii=False, indent=2)

    def to_dict(self) -> Dict:
        """转换为字典用于保存"""
        return {
            "Name": self.name,
            "Province": self.province,
            "Prize（yuan)": self.prize,
            "ID": self.id,
            "ProvinceID": self.province_id,
            "MerchantID": self.merchant_id,
            "Kind": self.kind,
            "Comments": self.comments,
            "ModifyLogs": self.modify_logs
        }


# 商品子类
class Food(Product):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class Clothing(Product):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class Book(Product):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class ElectronicProducts(Product):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

class DailyProduct(Product):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


def display_search_results(products: List, customer: Customer, keyword: str):
    """显示搜索结果并让用户选择"""
    if not products:
        print(bi("未找到匹配的商品！", "No matching products found!"))
        customer.add_search_history(keyword, 0)
        return None
    
    # 记录搜索历史
    customer.add_search_history(keyword, len(products))
    
    # 显示搜索结果
    print(bi(f"\n🔍 搜索关键词：'{keyword}'", f"Search keyword: '{keyword}'"))
    print(bi(f"📊 找到 {len(products)} 个匹配商品：", f"Found {len(products)} matching products:"))
    print("=" * 60)
    
    for i, p in enumerate(products, 1):
        print(f"{i:2d}. 📦 {p.name}")
        print(f"     💰 价格：{p.prize}元")
        print(f"     🏷️  类别：{p.kind}  📍 产地：{p.province}")
        print(f"     🆔 ID：{p.id}")
        print("-" * 40)
    
    # 选择商品
    while True:
        try:
            choice = input(bi(f"\n请选择要查看的商品（输入序号 1-{len(products)}，或输入 0 返回）：", f"Select a product to view (enter 1-{len(products)}, or 0 to go back): ")).strip()
            if choice == "0":
                return None
            
            idx = int(choice) - 1
            if 0 <= idx < len(products):
                return products[idx]
            else:
                print(bi(f"请输入 1-{len(products)} 之间的数字！", f"Please enter a number between 1 and {len(products)}!"))
        except ValueError:
            print(bi("请输入有效的数字！", "Please enter a valid number!"))
        except KeyboardInterrupt:
            print(bi("\n操作已取消", "Operation cancelled"))
            return None

def customer_menu(customer: Customer):
    """顾客菜单"""
    while True:
        print("\n" + "="*50)
        print(bi("🛒 欢迎使用商品搜索系统", "Welcome to the product search system"))
        print("="*50)
        print(bi("1. 🔍 快速搜索商品", "1. Quick search"))
        print(bi("2. 🔎 高级搜索", "2. Advanced search"))
        print(bi("3. 📋 查看搜索历史", "3. View search history"))
        print(bi("4. ❌ 退出系统", "4. Exit"))
        choice = input(bi("\n请选择功能（1-4）：", "Choose an option (1-4): ")).strip()
        
        if choice == "1":
            keyword = input(bi("\n🔍 请输入搜索关键词：", "Enter search keyword: ")).strip()
            if not keyword:
                print(bi("❌ 搜索关键词不能为空！", "Search keyword cannot be empty!"))
                continue
            
            products = Product.fuzzy_search(keyword)
            product = display_search_results(products, customer, keyword)
            if product:
                show_product_details(product, customer)
        
        elif choice == "2":
            advanced_search_menu(customer)
        
        elif choice == "3":
            show_search_history(customer)
        
        elif choice == "4":
            print(bi("\n👋 感谢使用，再见！", "Thanks for using, goodbye!"))
            break
        
        else:
            print(bi("❌ 输入无效，请重新选择！", "Invalid input, please try again!"))

def advanced_search_menu(customer: Customer):
    """高级搜索菜单"""
    print("\n🔎 高级搜索")
    print("-" * 30)
    
    criteria = {}
    
    # 名称搜索
    name = input("商品名称（可选，按回车跳过）：").strip()
    if name:
        criteria['name'] = name
    
    # 类别搜索
    kind = input("商品类别（可选，按回车跳过）：").strip()
    if kind:
        criteria['kind'] = kind
    
    # 产地搜索
    province = input("产地（可选，按回车跳过）：").strip()
    if province:
        criteria['province'] = province
    
    # 价格范围
    try:
        min_price = input("最低价格（可选，按回车跳过）：").strip()
        if min_price:
            criteria['min_price'] = float(min_price)
        
        max_price = input("最高价格（可选，按回车跳过）：").strip()
        if max_price:
            criteria['max_price'] = float(max_price)
    except ValueError:
        print("❌ 价格必须是数字！")
        return
    
    # 已移除库存字段（stock），不再提供库存筛选项
    
    if not criteria:
        print("❌ 请至少输入一个搜索条件！")
        return
    
    products = Product.advanced_search(criteria)
    keyword = "高级搜索: " + ", ".join([f"{k}={v}" for k, v in criteria.items()])
    product = display_search_results(products, customer, keyword)
    if product:
        show_product_details(product, customer)

def show_search_history(customer: Customer):
    """显示搜索历史"""
    history = customer.get_search_history()
    if not history:
        print("\n📋 暂无搜索历史")
        return
    
    print("\n📋 搜索历史")
    print("=" * 50)
    for i, record in enumerate(reversed(history), 1):
        print(f"{i:2d}. 🔍 {record['keyword']}")
        print(f"     ⏰ {record['timestamp']}  📊 找到 {record['results_count']} 个结果")
        print("-" * 30)
    
    # 选择历史搜索
    try:
        choice = input(f"\n选择要重新搜索的历史记录（1-{len(history)}，或按回车返回）：").strip()
        if choice:
            idx = int(choice) - 1
            if 0 <= idx < len(history):
                keyword = history[-(idx+1)]['keyword']
                if keyword.startswith("高级搜索: "):
                    print("❌ 高级搜索记录无法直接重新搜索")
                else:
                    products = Product.fuzzy_search(keyword)
                    product = display_search_results(products, customer, keyword)
                    if product:
                        show_product_details(product, customer)
    except (ValueError, IndexError):
        print("❌ 输入无效！")

def show_product_details(product: Product, customer: Customer):
    """显示商品详情并处理用户操作"""
    while True:
        print("\n" + "="*60)
        print(f"📦 商品详情：{product.name}")
        print("="*60)
        print(f"💰 价格：{product.prize}元")
        print(f"🏷️  类别：{product.kind}")
        print(f"📍 产地：{product.province}（{product.province_id}）")
        print(f"🆔 商品ID：{product.id}")
        print(f"👤 商家ID：{product.merchant_id}")
        
        print("\n📝 评价操作：")
        print("1. 👀 查看评价")
        print("2. ✍️  添加评价")
        print("3. 🔙 返回主菜单")
        
        choice = input("\n请选择操作（1-3）：").strip()
        
        if choice == "1":
            show_product_comments(product, customer)
        elif choice == "2":
            add_product_comment(product, customer)
        elif choice == "3":
            break
        else:
            print("❌ 输入无效，请重新选择！")

def show_product_comments(product: Product, customer: Customer):
    """显示商品评价"""
    if not product.comments:
        print("\n📝 暂无评价！")
        return
    
    print("\n📝 评价筛选：")
    print("1. 全部评价  2. 好评  3. 中评  4. 差评")
    filter_choice = input("请选择评价类型（1-4）：").strip()
    filter_map = {"1": "全部", "2": "好评", "3": "中评", "4": "差评"}
    filter_type = filter_map.get(filter_choice, "全部")
    
    print("\n📊 排序方式：")
    print("1. 最新  2. 最热")
    sort_choice = input("请选择排序方式（1-2）：").strip()
    sort_map = {"1": "最新", "2": "最热"}
    sort_type = sort_map.get(sort_choice, "最新")
    
    filtered = product.filter_comments(filter_type, sort_type)
    print(f"\n📝 {filter_type}评价（{sort_type}排序）")
    print("="*50)
    
    for i, cmt in enumerate(filtered, 1):
        print(f"{i:2d}. 👤 {cmt['nickname']}（{cmt['timestamp']}）")
        print(f"     ⭐ 评分：商品{cmt['product_rating']} 商家{cmt['merchant_rating']} 物流{cmt['logistics_rating']}")
        print(f"     💬 评价：{cmt['text']}")
        if cmt["merchant_reply"]:
            print(f"     🏪 商家回复：{cmt['merchant_reply']['text']}（{cmt['merchant_reply']['timestamp']}）")
        print(f"     👍 点赞：{cmt['likes']} | 💬 回复：{len(cmt['replies'])}")
        print("-" * 40)
    
    # 评价互动
    if filtered:
        try:
            cmt_idx = int(input(f"\n选择要互动的评价（1-{len(filtered)}，0返回）：").strip()) - 1
            if cmt_idx == -1:
                return
            target_cmt = filtered[cmt_idx]
            
            action = input("选择操作（1.点赞 2.回复）：").strip()
            if action == "1":
                product.like_comment(customer, target_cmt["comment_id"])
            elif action == "2":
                reply_text = input("请输入回复内容：").strip()
                product.reply_to_comment(customer, target_cmt["comment_id"], reply_text)
            else:
                print("❌ 输入无效！")
        except (ValueError, IndexError):
            print("❌ 输入无效！")

def add_product_comment(product: Product, customer: Customer):
    """添加商品评价"""
    print("\n✍️ 添加评价")
    print("-" * 30)
    try:
        product_score = int(input("1. 商品满意度（1-5星）：").strip())
        merchant_score = int(input("2. 商家满意度（1-5星）：").strip())
        logistics_score = int(input("3. 物流满意度（1-5星）：").strip())
        
        if not (1 <= product_score <= 5 and 1 <= merchant_score <= 5 and 1 <= logistics_score <= 5):
            raise ValueError
        
        text = input("4. 文字评价：").strip()
        
        product.add_comment(customer, {
            "商品满意度": "★" * product_score,
            "商家满意度": "★" * merchant_score,
            "物流满意度": "★" * logistics_score,
            "文字评价": text
        })
    except ValueError:
        print("❌ 评分必须是1-5之间的数字！")




def merchant_menu(merchant: Merchant):
    """商家菜单"""
    while True:
        print("\n" + "="*50)
        print("🏪 商家管理系统")
        print("="*50)
        print("1. 📦 查看我的商品")
        print("2. ❌ 退出系统")
        choice = input("\n请选择功能（1-2）：").strip()
        
        if choice == "1":
            products = Product.get_merchant_products(merchant.user_id)
            if not products:
                print("\n📦 您暂无商品！")
                continue
            
            # 显示商家商品
            print("\n📦 我的商品：")
            print("="*50)
            for i, p in enumerate(products, 1):
                print(f"{i:2d}. 📦 {p.name}")
                print(f"     🆔 ID：{p.id}")
                print(f"     💰 价格：{p.prize}元  🏷️ 类别：{p.kind}")
                print("-" * 40)
            
            # 选择商品
            try:
                idx = int(input(f"\n选择要操作的商品（1-{len(products)}）：").strip()) - 1
                product = products[idx]
            except (ValueError, IndexError):
                print("❌ 输入无效！")
                continue
            
            # 商品操作
            while True:
                print(f"\n📦 操作商品：{product.name}")
                print("-" * 40)
                print("1. 👀 查看评价")
                print("2. 💬 回复评价")
                print("3. ✏️  修改商品信息")
                print("4. 🔙 返回上一级")
                
                sub_choice = input("\n请选择（1-4）：").strip()
                
                if sub_choice == "1":
                    show_merchant_product_comments(product)
                elif sub_choice == "2":
                    reply_to_product_comment(product, merchant)
                elif sub_choice == "3":
                    update_product_info(product, merchant)
                elif sub_choice == "4":
                    break
                else:
                    print("❌ 输入无效！")
        
        elif choice == "2":
            print("\n👋 感谢使用，再见！")
            break
        else:
            print("❌ 输入无效，请重新选择！")

def show_merchant_product_comments(product: Product):
    """商家查看商品评价"""
    if not product.comments:
        print("\n📝 暂无评价！")
        return
    
    print("\n📝 所有评价")
    print("="*50)
    for i, cmt in enumerate(product.comments, 1):
        print(f"{i:2d}. 👤 {cmt['nickname']}（{cmt['timestamp']}）")
        print(f"     ⭐ 评分：商品{cmt['product_rating']} 商家{cmt['merchant_rating']} 物流{cmt['logistics_rating']}")
        print(f"     💬 评价：{cmt['text']}")
        if cmt["merchant_reply"]:
            print(f"     🏪 已回复：{cmt['merchant_reply']['text']}")
        print(f"     👍 点赞：{cmt['likes']} | 💬 回复：{len(cmt['replies'])}")
        print("-" * 40)

def reply_to_product_comment(product: Product, merchant: Merchant):
    """商家回复评价"""
    if not product.comments:
        print("\n📝 暂无评价可回复！")
        return
    
    print("\n💬 回复评价")
    print("-" * 30)
    for i, cmt in enumerate(product.comments, 1):
        print(f"{i:2d}. 👤 {cmt['nickname']}：{cmt['text']}")
        if cmt["merchant_reply"]:
            print(f"     🏪 已回复：{cmt['merchant_reply']['text']}")
        print("-" * 30)
    
    try:
        cmt_idx = int(input(f"\n选择要回复的评价（1-{len(product.comments)}）：").strip()) - 1
        target_cmt = product.comments[cmt_idx]
        reply_text = input("请输入回复内容：").strip()
        product.merchant_reply(merchant, target_cmt["comment_id"], reply_text)
    except (ValueError, IndexError):
        print("❌ 输入无效！")

def update_product_info(product: Product, merchant: Merchant):
    """修改商品信息"""
    print("\n✏️ 修改商品信息")
    print("-" * 30)
    print("可修改项：1.价格 2.产地")
    items = input("请选择要修改的项目（用逗号分隔，如1,2）：").strip().split(',')
    new_data = {}
    
    for item in items:
        if item == "1":
            try:
                new_prize = float(input("请输入新价格：").strip())
                new_data["prize"] = new_prize
            except ValueError:
                print("❌ 价格必须是数字！")
        elif item == "2":
            new_province = input("请输入新产地：").strip()
            new_data["province"] = new_province
        else:
            print(f"❌ 无效选项：{item}")
    
    if new_data:
        reason = input("请输入修改原因：").strip()
        if product.update_info(merchant, new_data, reason):
            print("✅ 修改成功！")
            print(f"更新后信息：价格{product.prize}元，产地{product.province}")
        
        # 查看修改日志
        if input("\n是否查看修改日志？（y/n）：").strip().lower() == "y":
            if product.modify_logs:
                print("\n📋 修改日志")
                print("="*50)
                for log in product.modify_logs:
                    print(f"⏰ 时间：{log['timestamp']}")
                    print(f"✏️ 修改：{log['old_data']} → {log['new_data']}")
                    print(f"💭 原因：{log['reason']}\n")
            else:
                print("📋 暂无修改日志！")


def main():
    """主程序入口"""
    print("="*60)
    print("🛒 欢迎使用商品搜索与评价系统")
    print("="*60)
    
    while True:
        print("\n👥 请选择角色：")
        print("1. 👤 顾客")
        print("2. 🏪 商家")
        print("3. ❌ 退出系统")
        
        role = input("\n请选择（1-3）：").strip()
        
        if role == "1":
            # 顾客登录
            print("\n👤 顾客登录")
            print("-" * 30)
            user_id = input("请输入顾客ID：").strip()
            nickname = input("请输入昵称：").strip()
            
            if not user_id or not nickname:
                print("❌ ID和昵称不能为空！")
                continue
            
            customer = Customer(user_id, nickname)
            print(f"\n✅ 欢迎，{nickname}！")
            customer_menu(customer)
            break
            
        elif role == "2":
            # 商家登录
            print("\n🏪 商家登录")
            print("-" * 30)
            user_id = input("请输入商家ID：").strip()
            shop_name = input("请输入店铺名称：").strip()
            
            if not user_id or not shop_name:
                print("❌ ID和店铺名称不能为空！")
                continue
            
            merchant = Merchant(user_id, shop_name)
            print(f"\n✅ 欢迎，{shop_name}！")
            merchant_menu(merchant)
            break
            
        elif role == "3":
            print("\n👋 感谢使用，再见！")
            break
            
        else:
            print("❌ 请输入1-3之间的数字！")


if __name__ == "__main__":
    main()
